﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using TowerDefenderSilverlight.Model;
using System.Xml;
using System.Xml.Linq;

namespace TowerDefenderSilverlight.Data
{
    public class FileManager
    {
        /// <summary>
        /// Create a Map object from an xml file
        /// </summary>
        /// <param name="path">The file path</param>
        /// <returns></returns>
        public static Map LoadMap(XDocument doc)
        {
            Map map = null;

            try
            {
                var steps = from step in doc.Descendants("Cell")
                            select new
                            {
                                X = step.Attribute("X"),
                                Y = step.Attribute("Y")
                            };
            
                MapPath mapPath = new MapPath();

                foreach (var step in steps)
                {
                    int X = int.Parse(step.X.Value);
                    int Y = int.Parse(step.Y.Value);
                    mapPath.AddStep(X,Y); 
                }

                var mapSettings = (from m in doc.Descendants("Map")
                            select new
                            {
                                width = int.Parse(m.Attribute("width").Value),
                                length = int.Parse(m.Attribute("length").Value)
                            }).First();

                map = new Map(mapSettings.width, mapSettings.length, mapPath);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            return map;
        }
    }
}
